package com.liu.security.handler;

import com.liu.security.enums.HttpStateEnum;
import com.liu.security.exception.CustomException;
import com.liu.security.pojo.Authoritie;
import com.liu.security.pojo.User;
import com.liu.security.pojo.UserDetail;
import com.liu.security.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * 用户对象拦截验证
 */
@Component
@AllArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

    private final UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByName(username);
        if(user == null){
            throw new CustomException("用户不存在！",HttpStateEnum.TOKENERROR.getCode());
        }
        user.setAuthorities(new ArrayList<Authoritie>());

        return new UserDetail(user);
    }
}